package org.jsola.hr.service.impl;

import cn.hutool.core.date.DateUtil;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dao.ICrmVisitRecordDAO;
import org.jsola.hr.dto.CrmCustomerInfoUpdateDTO;
import org.jsola.hr.dto.CrmVisitRecordAddDTO;
import org.jsola.hr.dto.CrmVisitRecordUpdateDTO;
import org.jsola.hr.entity.CrmVisitRecordDO;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.hr.query.CrmMemberQuery;
import org.jsola.hr.query.CrmVisitRecordQuery;
import org.jsola.hr.service.ICrmCustomerInfoService;
import org.jsola.hr.service.ICrmMemberService;
import org.jsola.hr.service.ICrmVisitRecordService;
import org.jsola.hr.vo.CrmMemberListVO;
import org.jsola.hr.vo.CrmMemberVO;
import org.jsola.hr.vo.CrmVisitRecordListVO;
import org.jsola.hr.vo.CrmVisitRecordVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.entity.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 拜访记录表
 *
 * @author zhr
 */
@Service("hrCrmVisitRecordServiceImpl")
public class CrmVisitRecordServiceImpl implements ICrmVisitRecordService {

    @Autowired
    private ICrmVisitRecordDAO crmVisitRecordDAO;
    @Autowired
    private ICrmMemberService crmMemberService;
    @Autowired
    private IUserProviderService userProviderService;
    @Autowired
    private ICrmCustomerInfoService crmCustomerInfoService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public CrmVisitRecordVO save(CrmVisitRecordAddDTO crmVisitRecordAddDTO, TokenUser tokenUser) {
        CrmMemberQuery crmMemberQuery = new CrmMemberQuery();
        crmMemberQuery.setUserId(tokenUser.getUserId());
        List<CrmMemberListVO> select = crmMemberService.select(crmMemberQuery, tokenUser.getSiteId());
        if(CollectionUtils.isEmpty(select)) {
            throw new ParamException("没有操作权限");
        }
        crmVisitRecordAddDTO.setMemberId(select.get(0).getId());
        crmVisitRecordAddDTO.setMemberName(tokenUser.getUserName());
        // 转DO
        CrmVisitRecordDO crmVisitRecordDO = crmVisitRecordAddDTO.to(CrmVisitRecordDO.class);
        // 保存
        crmVisitRecordDO = save(crmVisitRecordDO, tokenUser.getSiteId(), tokenUser.getUserId());

        //查询最后一次拜访更新到客户详情
        CrmVisitRecordVO crmVisitRecordVO = crmVisitRecordDAO.getNearVisitDate(crmVisitRecordAddDTO.getCustomerId());
        CrmCustomerInfoUpdateDTO crmCustomerInfoUpdateDTO = new CrmCustomerInfoUpdateDTO();
        crmCustomerInfoUpdateDTO.setId(crmVisitRecordVO.getCustomerId());
        crmCustomerInfoUpdateDTO.setLastVisitTime(crmVisitRecordVO.getVisitTime());
        crmCustomerInfoService.update(crmCustomerInfoUpdateDTO,tokenUser);
        return crmVisitRecordDO.to(CrmVisitRecordVO.class);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(CrmVisitRecordUpdateDTO crmVisitRecordUpdateDTO, TokenUser tokenUser) {
        //转DO
        CrmVisitRecordDO crmVisitRecordDO = crmVisitRecordUpdateDTO.to(CrmVisitRecordDO.class);
        //根据主键更新，只更新非null值
        return updateByIdSelective(crmVisitRecordDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... crmVisitRecordIds) {
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) crmVisitRecordIds);
    }


    @Override
    public CrmVisitRecordVO selectById(String crmVisitRecordId, String siteId) {
        CrmVisitRecordDO crmVisitRecordDO = selectDOById(crmVisitRecordId, siteId);
        if (crmVisitRecordDO == null) {
            return null;
        }
        return crmVisitRecordDO.to(CrmVisitRecordVO.class);
    }

    @Override
    public List<CrmVisitRecordListVO> select(CrmVisitRecordQuery crmVisitRecordQuery, String siteId) {
        List<CrmVisitRecordDO> crmVisitRecordDOList = selectDO(crmVisitRecordQuery, siteId);
        if(CollectionUtils.isEmpty(crmVisitRecordDOList)) {
            return crmVisitRecordDOList == null ? null : new ArrayList<>();
        }
        return crmVisitRecordDOList.stream()
                .map(crmVisitRecordDO -> crmVisitRecordDO.to(CrmVisitRecordListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(CrmVisitRecordQuery crmVisitRecordQuery, String siteId) {
        Example example = buildExample(crmVisitRecordQuery,siteId);
        return crmVisitRecordDAO.selectCountByExample(example);
    }

    @Override
    public Page<CrmVisitRecordListVO> selectPage(CrmVisitRecordQuery crmVisitRecordQuery, String siteId) {
        Example example = buildExample(crmVisitRecordQuery,siteId);
        Page<CrmVisitRecordDO> page = crmVisitRecordDAO.selectPageByExample(example,
                crmVisitRecordQuery.getPageNo(),
                crmVisitRecordQuery.getPageSize());
        Page<CrmVisitRecordListVO> page1 = page.to(CrmVisitRecordListVO.class);
        for (CrmVisitRecordListVO entity : page1.getEntities()) {
            CrmMemberVO crmMemberVO = crmMemberService.selectById(entity.getMemberId(), siteId);
            ParamException.notNull(crmMemberVO,"无操作权限");
            UserDO userDO = userProviderService.selectUserById(crmMemberVO.getUserId());
            entity.setPhone(userDO.getPhone());
        }
        return page1;
    }

    @Override
    public CrmVisitRecordDO selectDOById(String crmVisitRecordId, String siteId) {
        return listById(crmVisitRecordId, siteId);
    }

    @Override
    public List<CrmVisitRecordDO> selectDO(CrmVisitRecordQuery crmVisitRecordQuery, String siteId) {
        Example example = buildExample(crmVisitRecordQuery,siteId);
        return crmVisitRecordDAO.selectByExample(example);
    }


    /**
     * 根据查询参数，构建example

     * @param crmVisitRecordQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(CrmVisitRecordQuery crmVisitRecordQuery, String siteId) {
        Example example = new Example(CrmVisitRecordDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);

        if(crmVisitRecordQuery.getTimeStart() != null && crmVisitRecordQuery.getTimeEnd() != null){
            Date startDate = DateUtil.parse(crmVisitRecordQuery.getTimeStart(), "yyyy-MM-dd");
            Date endDate = DateUtil.parse(crmVisitRecordQuery.getTimeEnd(), "yyyy-MM-dd");
            example.and().andGreaterThanOrEqualTo("visitTime",startDate)
                    .andLessThanOrEqualTo("visitTime",endDate);
        }
        if(!StringUtils.isEmpty(crmVisitRecordQuery.getCustomerId())){
            example.and().andEqualTo("customerId",crmVisitRecordQuery.getCustomerId());
        }
        // 排序
        ExampleKit.setExampleOrder(example,crmVisitRecordQuery.getOrders());
        return example;
    }
}




